package com.niiwoo.civet.mobile.lanmao.handler;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.account.constant.RedisKeyConstant;
import com.niiwoo.civet.account.dto.request.CompanyAccountRequestDTO;
import com.niiwoo.civet.account.dto.response.AccountBaseResponse;
import com.niiwoo.civet.account.enums.CompanyAccountStatusEnums;
import com.niiwoo.civet.account.service.AccountCompanyDubboService;
import com.niiwoo.civet.account.service.AccountDubboService;
import com.niiwoo.civet.user.dto.request.OrganizationRequestDTO;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.tripod.lanmao.enums.LanMaoDirectServiceNameEnum;
import com.niiwoo.tripod.provider.exception.BizException;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Date;

@Component
public class DirectChangeCompanyInfomationNotifyHandler implements LanMaoNotifyHandler {

    public static final Logger logger = LoggerFactory.getLogger(DirectChangeCompanyInfomationNotifyHandler.class);

    @Reference(version = "1.0.0")
    private AccountDubboService accountDubboService;

    @Reference(version = "1.0.0")
    private OrganizationDubboService organizationDubboService;

    @Reference(version = "1.0.0")
    private AccountCompanyDubboService accountCompanyDubboService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean supports(String serviceName) {
        return LanMaoDirectServiceNameEnum.ENTERPRISE_INFORMATION_UPDATE_API.name().equals(serviceName);
    }

    @Override
    public HandleResult handle(JSONObject json) {
        logger.info("直连修改企业资料回调处理###报文###data={}", json.toString());

        DirectChangeCompanyInfomationResponse response = json.toJavaObject(DirectChangeCompanyInfomationResponse.class);
        if (response.isCallSuccess()) {
            OrganizationRequestDTO orgInfoReqDto = null;

            CompanyAccountRequestDTO reqDto = new CompanyAccountRequestDTO();
            reqDto.setAccountNo(response.getPlatformUserNo());
            reqDto.setUpdateMangerId(1L);// 系统修改默认id
            reqDto.setUpdateTime(new Date());

            if (response.getReviewStatus().equals(CompanyAccountStatusEnums.PASSED.name())
                    || response.getReviewStatus().equals(CompanyAccountStatusEnums.REFUSED.name())) {
                String redisKey = RedisKeyConstant.UPLOADED_COMPANY_INFO_KEY_PREFIX + response.getPlatformUserNo();
                redisTemplate.delete(redisKey);
            }

            // 审核拒绝修改存管账户的状态
            if (response.getReviewStatus().equals(CompanyAccountStatusEnums.REFUSED.name())) {
                reqDto.setAuditStatus(CompanyAccountStatusEnums.REFUSED.getStatus());
            }

            // 审核通过修改存管账户同时修改用户中心的企业资料
            if (response.getReviewStatus().equals(CompanyAccountStatusEnums.PASSED.name())) {
                orgInfoReqDto = new OrganizationRequestDTO();

                reqDto.setCompanyName(response.getEnterpriseName());
                reqDto.setBankLicence(response.getBankLicense());
                reqDto.setOrgNo(response.getOrgNo());
                reqDto.setBusinessLicense(response.getBusinessLicense());
                reqDto.setTaxNo(response.getTaxNo());
                reqDto.setUnifiedCode(response.getUnifiedCode());
                reqDto.setLegalPersonName(response.getLegal());
                reqDto.setLegalPersonIdCard(response.getLegalIdCardNo());
                reqDto.setContactName(response.getContact());
                reqDto.setContactMobileNo(response.getContactPhone());
                reqDto.setCreditCode(response.getCreditCode());
                reqDto.setAuditStatus(CompanyAccountStatusEnums.PASSED.getStatus());

                // 修改用户中心企业资料
                orgInfoReqDto.setOrganizationName(response.getEnterpriseName());
                orgInfoReqDto.setAccountOpeningBankLicense(response.getBankLicense());
                orgInfoReqDto.setOrgNo(response.getOrgNo());
                orgInfoReqDto.setCharterCode(response.getBusinessLicense());
                orgInfoReqDto.setTaxId(response.getTaxNo());
                orgInfoReqDto.setUnifiedSocialCreditCode(response.getUnifiedCode());
                orgInfoReqDto.setRepresentative(response.getLegal());
                orgInfoReqDto.setLegalPersonCertNumber(response.getLegalIdCardNo());
                orgInfoReqDto.setCorporateContactsName(response.getContact());
                orgInfoReqDto.setContactsPhoneName(response.getContactPhone());
                orgInfoReqDto.setInstitutionalReditCode(response.getCreditCode());
                orgInfoReqDto.setUpdateManager(1L); // 系统修改默认id
                orgInfoReqDto.setUpdatetime(new Date());

                logger.info("直连修改企业资料回调处理###修改企业资料信息请求###request={}", JSON.toJSONString(orgInfoReqDto));
            }

            logger.info("直连修改企业资料回调处理###修改企业账户信息请求###request={}", JSON.toJSONString(reqDto));
            boolean isUpdateSuccess;
            try {
                isUpdateSuccess = accountCompanyDubboService.updateAccountCompany(reqDto);
                if (orgInfoReqDto != null) {
                    if (isUpdateSuccess) {
                        AccountBaseResponse accountBaseResponse = accountDubboService.loadAccountByAccountNo(reqDto.getAccountNo());
                        orgInfoReqDto.setId(accountBaseResponse.getOrgId());
                        isUpdateSuccess = organizationDubboService.updateUserOrgInfo(orgInfoReqDto);
                    }
                }
                logger.info("直连修改企业资料回调处理###修改响应###response={}", isUpdateSuccess);
            } catch (BizException e) {
                logger.error("直连修改企业资料回调处理###修改异常###errorCode={}, errorMessage={}", e.getErrorCode(), e.getMessage());
                throw e;
            } catch (Exception e) {
                logger.error(String.format("直连修改企业资料回调处理###未知异常###errorMessage=%s", e.getMessage()), e);
                throw new BizException("SYS9999");
            }

            HandleResult result = new HandleResult();
            result.setNeedAck(true);
            result.setData(Collections.singletonMap("orderStatus", isUpdateSuccess ? "SUCCESS" : "FAIL"));
            result.setRequestNo(response.getRequestNo());

            return result;
        }

        throw new BizException(true, null, "直连修改企业资料回调处理失败");
    }

    @Setter
    @Getter
    private static class DirectChangeCompanyInfomationResponse {

        private static final String CALL_SUCCESS_CODE = "0";

        // 请求流水号
        private String requestNo;

        // 平台用户编号
        private String platformUserNo;

        // 调用状态(0 为调用成功、1 为失败,返回 1 时请看【调用失败错误码】及错误码)
        private String code;

        // 审核状态(PASSED表示审核通过，REFUSED表示审核拒绝)
        private String reviewStatus;

        // 审核描述信息，审核拒绝会返回拒绝原因
        private String reviewDescription;

        // 企业资质编码是否发生变更(YES变更，NO未变更)
        private String qualificationModify;

        // 变更后企业名称
        private String enterpriseName;

        // 变更后开户银行许可证号
        private String bankLicense;

        // 变更后组织机构代码
        private String orgNo;

        // 变更后营业执照编号
        private String businessLicense;

        // 变更后税务登记号
        private String taxNo;

        // 变更后统一社会信用代码（可替代三证）
        private String unifiedCode;

        // 变更后法人姓名
        private String legal;

        // 变更后法人证件号码
        private String legalIdCardNo;

        // 变更后企业联系人
        private String contact;

        // 变更后联系人手机号
        private String contactPhone;

        // 描述信息
        private String description;

        // 变更后机构信用代码
        private String creditCode;

        private boolean isCallSuccess() {
            return StringUtils.isNotBlank(code) && CALL_SUCCESS_CODE.equals(code);
        }

    }
}
